package com.we823.cms.controller.manage.sys;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import com.github.pagehelper.PageInfo;
import com.we823.cms.common.web.pageable.PageRequest;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.we823.cms.common.WebConstants;
import com.we823.cms.common.utils.RequestUtil;
import com.we823.cms.controller.manage.AbstractManageController;
import com.we823.cms.model.sys.Permission;
import com.we823.cms.model.sys.Resource;
import com.we823.cms.model.sys.Role;
import com.we823.cms.model.sys.RoleResourcePermission;
import com.we823.cms.repository.service.sys.PermissionService;
import com.we823.cms.repository.service.sys.ResourceService;
import com.we823.cms.repository.service.sys.RoleResourcePermissionService;
import com.we823.cms.repository.service.sys.RoleService;

@Controller
@RequestMapping(WebConstants.MANAGE_URL+"/role")
public class RoleManageController extends AbstractManageController<Role, Integer> {

	private String baseUrl = WebConstants.MANAGE_URL+"/role/";
	
	@Autowired
	private ResourceService resourceService;
	@Autowired
	private PermissionService permissionService;
	@Autowired
	private RoleResourcePermissionService roleResourcePermissionService;
	
	private RoleService roleService;
	@Autowired
	public RoleManageController(RoleService roleService) {
		super(roleService);
		super.baseUrl = baseUrl;
		super.entityName="role";
		
		this.roleService=roleService;
	}

	@Override
	public PageInfo<Role> getData(PageRequest pageRequest,
								  HttpServletRequest request, Model model, boolean pageable) {
		PageInfo<Role> rolePage;
		if (pageable) {
			rolePage = roleService.findAll(pageRequest);
		} else {
			rolePage = new PageInfo<>(roleService.findAll());
		}
		return rolePage;
	}
	
	@Override
	public String preAdd(Model model) {
		String result = super.preAdd( model);

		List<Resource> resourceModels = resourceService.findByParentid(0,
				true);

		model.addAttribute("resources", resourceModels);

		List<Permission> permissionModels = permissionService.findAll();
		model.addAttribute("permissions", permissionModels);
		return result;
	}

	@RequestMapping("addEx")
	public String add(HttpServletRequest request,Role entity,
			BindingResult result) {
		String resultUrl = super.add(entity, result);
		int roleId = (entity==null) ? 0 : entity.getId();
		if (roleId>0) {
			String[] resourceIdList = RequestUtil.getValuesByName(request, "resourceIds");
			if(resourceIdList!=null && resourceIdList.length>0) {
				List<RoleResourcePermission> roleResourcePermissionModels = new ArrayList<>();
				for (String resourceId : resourceIdList) {
					int rId=0;
					if(StringUtils.isNumeric(resourceId)) {
						rId = Integer.parseInt(resourceId);
						String[] permissionIdList = RequestUtil.getValuesByName(request, "permission_"+resourceId);
						String permissionIds="";
						if(permissionIdList!=null) {
							permissionIds = StringUtils.join(permissionIdList,",");
						}
						
						RoleResourcePermission roleResourcePermissionModel = new RoleResourcePermission();
						roleResourcePermissionModel.setRoleId(roleId);
						roleResourcePermissionModel.setResourceId(rId);
						roleResourcePermissionModel.setPermissionIds(permissionIds);
						roleResourcePermissionModels.add(roleResourcePermissionModel);
					}
				}
				
				roleResourcePermissionService.save(roleResourcePermissionModels);
			}
		}
		
		return resultUrl;
	}
	@Override
	public String preEdit(@RequestParam(required = true, value = "id", defaultValue = "-1") Integer key,
			Model model) {
		List<Resource> resourceModels = resourceService.findByParentid(0,
				true);

		model.addAttribute("resources", resourceModels);

		List<Permission> permissionModels = permissionService.findAll();
		model.addAttribute("permissions", permissionModels);

		return super.preEdit(key, model);
	}

	@RequestMapping("editEx")
	public String edit(HttpServletRequest request, Role entity,
			BindingResult result) {
		String resultUrl = super.edit(entity, result);
		String[] resourceIdList = RequestUtil.getValuesByName(request,
				"resourceIds");

		int roleId = (entity != null) ? entity.getId() : 0;
		if (roleId > 0) {
			List<RoleResourcePermission> oldRoleResourcePermissionModels = roleResourcePermissionService
					.findByRoleid(roleId);

			List<RoleResourcePermission> needDeleteList = new ArrayList<>();
			List<RoleResourcePermission> needUpdateList = new ArrayList<>();
			List<RoleResourcePermission> needAddList = new ArrayList<>();

			if (resourceIdList != null && resourceIdList.length > 0) {
				List<RoleResourcePermission> roleResourcePermissionModels = new ArrayList<>();
				for (String resourceId : resourceIdList) {
					int rId = 0;
					if (StringUtils.isNumeric(resourceId)) {
						rId = Integer.parseInt(resourceId);
						String[] permissionIdList = RequestUtil
								.getValuesByName(request, "permission_"
										+ resourceId);
						String permissionIds = "";
						if (permissionIdList != null) {
							permissionIds = StringUtils.join(permissionIdList,
									",");
						}

						RoleResourcePermission roleResourcePermissionModel = new RoleResourcePermission();
						roleResourcePermissionModel.setRoleId(roleId);
						roleResourcePermissionModel.setResourceId(rId);
						roleResourcePermissionModel
								.setPermissionIds(permissionIds);
						roleResourcePermissionModels
								.add(roleResourcePermissionModel);
					}
				}

				if (oldRoleResourcePermissionModels == null
						|| oldRoleResourcePermissionModels.size() == 0) {
					// 当原有的list为空，且目前的list不为空
					needAddList.addAll(roleResourcePermissionModels);
				} else {
					for (RoleResourcePermission oldPermissionModel : oldRoleResourcePermissionModels) {
						boolean isdel = true;
						for (RoleResourcePermission roleResourcePermissionModel : roleResourcePermissionModels) {
							if (oldPermissionModel.getResourceId() == roleResourcePermissionModel
									.getResourceId()) {
								isdel = false;
								break;
							}
						}
						if (isdel) {
							needDeleteList.add(oldPermissionModel);
						}
					}

					for (RoleResourcePermission roleResourcePermissionModel : roleResourcePermissionModels) {
						boolean isnew = true;
						for (RoleResourcePermission oldRoleResourcePermissionModel : oldRoleResourcePermissionModels) {
							if (oldRoleResourcePermissionModel.getResourceId() == roleResourcePermissionModel
									.getResourceId()) {
								roleResourcePermissionModel
										.setId(oldRoleResourcePermissionModel
												.getId());
								needUpdateList.add(roleResourcePermissionModel);
								isnew = false;
								break;
							}
						}
						if (isnew) {
							needAddList.add(roleResourcePermissionModel);
						}
					}
				}
			} else {
				// 当无资源选中时，所有原有的信息都需删除
				if (oldRoleResourcePermissionModels != null) {
					needDeleteList.addAll(oldRoleResourcePermissionModels);
				}
			}
			if (needAddList.size() > 0) {
				roleResourcePermissionService.save(needAddList);
			}
			if (needUpdateList.size() > 0) {
				roleResourcePermissionService.update(needUpdateList);
			}
			if (needDeleteList.size() > 0) {
				roleResourcePermissionService.delete(needDeleteList);
			}
		}
		return resultUrl;
	}

	@RequestMapping("getPermission")
	@ResponseBody
	public Model getPermissions(HttpServletRequest request, Model model) {

		int id = RequestUtil.getValueByName(request, "id", -1);
		List<Integer> roleIdList = new ArrayList<>();
		roleIdList.add(id);
		List<RoleResourcePermission> roleResourcePermissionModels = roleResourcePermissionService
				.findByRoleIdIn(roleIdList);
		model.addAttribute("permissions", roleResourcePermissionModels);
		return model;
	}

	@Override
	public void setIndetity() {
		setResourceIdentity("sys:role");
	}

}
